use super::{Data, SelectOption};
use leptos::*;
use std::{collections::HashMap, rc::Rc};

#[allow(non_snake_case)]
#[component]
pub fn Radio(
    label: &'static str,
    #[prop(into)] name: String,
    options: &'static [SelectOption],
) -> impl IntoView {
    let (getter, setter) = use_context::<(
        ReadSignal<HashMap<String, Data>>,
        WriteSignal<HashMap<String, Data>>,
    )>()
    .expect("to have found the setter provided");
    let name = Rc::new(name);
    let value = {
        let name = Rc::clone(&name);
        move || {
            let map = getter();
            let value = map
                .get(name.as_str())
                .and_then(|v| v.str())
                .unwrap_or_default();
            value.to_string()
        }
    };
    view! {
        <div class="flex flex-col gap-1 p-2">
            <label class="text-lg">{label}":"</label>
            <div class="flex gap-8 pl-2">
            {options
                .iter()
                .map(|option| {
                    let name = name.clone();
                    let opt = option.clone();
                    let checked = {
                        let current = value();
                        move ||  {
                        opt.value == current
                    }};
                    view! {
                        <div class="flex gap-1 text-base">
                            <input checked={checked} id=&option.label type="radio" name=name.as_ref() value=&option.value on:change= move |ev| {
                                let val = event_target_value(&ev);
                                let name = name.as_ref().to_string();
                                setter.update(|map| {
                                    let val = Data::String(val);
                                    map.insert(name,val);
                                })
                            } />
                            <label for=&option.label>{&option.label}</label>
                        </div>
                    }
                })
                .collect_view()}
            </div>
        </div>
    }
}
